package com.example.project.config.shiro;


import com.example.project.util.MD5Utils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Description: 自定义验证方式
 *
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {

    private Cache<String, AtomicInteger> passwordRetryCache;

    /**
     * 最大错误次数
     */
    private int retryMaxCount = 5;

    public CustomCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {

        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String username = (String) token.getPrincipal();
        String password = String.valueOf(token.getPassword());

        //retry count + 1
        AtomicInteger retryCount = passwordRetryCache.get(username);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }

        if (retryCount.incrementAndGet() > retryMaxCount) {
            //if retry count > 5 throw
            //throw new ExcessiveAttemptsException();
        }

        String hashed = info.getCredentials().toString();
        boolean matches = MD5Utils.checkpw(password, hashed);
        if (matches) {
            //clear retry count
            passwordRetryCache.remove(username);
        }

        return matches;
    }
}
